<template>
  <view class="law-container">
    <view
        class="top"
        :style="{
        background: 'url(' + homebg + ') no-repeat',
        backgroundSize: '100% 100%',
      }"
    >
      <text class="title">民事诉讼生成系统</text>
      <text class="sub-title">请编辑资料</text>
    </view>
    <view class="example">
      <u-steps :current="current" activeColor="#e43d33">
        <u-steps-item title="原告信息">
        </u-steps-item>
        <u-steps-item title="被告信息">
        </u-steps-item>
        <u-steps-item title="诉讼请求"></u-steps-item>
        <u-steps-item title="事实及理由"></u-steps-item>
      </u-steps>
      <view class="content">
        <plaintiffInfo :form="form" v-if="current==0" @updateForm="updateForm"></plaintiffInfo>
        <defendantInfo :form="form" v-else-if="current==1" @updateForm="updateForm"></defendantInfo>
        <request :form="form" v-else-if="current==2" @updateForm="updateForm"></request>
        <fact :form="form" v-else-if="current==3" @updateForm="updateForm"></fact>
      </view>
      <uni-pagination title="标题文字" total="40" @change="changePage"></uni-pagination>
      <view class="marginTop">
        <view class="flex-row">
          <view class="radio" v-if="!radiovalue" @click="changeState"></view>
          <view class="radio-checked" v-else @click="changeState">
            <u-icon name="checkbox-mark" color="#fff" size="10px"></u-icon>
          </view>
          <view class="flex-row">
            <text style="margin-left: 10rpx">我已阅读并同意</text>
            <text class="text-red" style="color: #e43d33"
            >《用户服务协议及隐私政策》
            </text
            >
          </view>
        </view>
      </view>
      <view class="bottom">
        <u-button color="#e43d33" @click="submit">提交</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import {isEmptyString} from "@/utils/common.js";
import bgBase64 from "@/static/const/bgBase64.js";
import config from "@/config.js";
import plaintiffInfo from "@/components/generateDoc/plaintffInfo.vue";
import defendantInfo from "@/components/generateDoc/defendantInfo";
import request from "@/components/generateDoc/request";
import fact from "@/components/generateDoc/fact";
import consultAndServiceConst from "@/static/const/consultAndServiceConst";
import orderManagement from "@/static/const/orderManagement";
import {getStorage} from "@/utils/auth";
import application from "@/static/const/application";

export default {
  components: {
    plaintiffInfo,
    defendantInfo,
    request,
    fact,
  },
  data() {
    return {
      imageURL: "/static/images/mine/txbg.png",
      detail: {},
      id: "",
      user: {},
      orderNumber: "",
      form: {
        plaintiffName: "",
        plaintiffSex: "",
        plaintiffID: "",
        plaintiffPhone: "",
        plaintiffAddress: "",
        defendantName: "",
        defendantSex: "",
        defendantID: "",
        defendantPhone: "",
        defendantAddress: "",
        lawsuitType: "民间借贷纠纷",
        owedMoney: "",
        repaymentTime: undefined,
        owedUse: "",
        repaymentMoney: "",
        interest: "",
        owedTime: undefined,
        IOUs: "",
        repayType: "",
        interestAll: "",
      },
      newForm: {},
      userId: "",
      radiovalue: false,
      radiolist: [
        {
          name: "我已阅读并同意《律师服务协议》",
        },
      ],
      rules: {},
      homebg: bgBase64.lawyerBg,

      actions: [{
        name: '男',
      },
        {
          name: '女',
        },
      ],
      typeActions: [{
        name: '民间借贷纠纷',
      },
        {
          name: '离婚纠纷',
        },
        {
          name: '买卖合同纠纷',
        },
      ],


      localPath: "",
      time: "",
      current: 0,
    };
  },
  onLoad(params) {
    //获取id
    this.id = params.id;
    this.user = getStorage(application.user);
    this.getDetail();
  },
  onReady() {
    //onReady 为uni-app支持的生命周期之一
    this.$nextTick(() => {
      // this.$refs.datetimePicker.setFormatter(this.formatter);
    });
  },
  methods: {
    getDetail() {
      this.$store
          .dispatch("GetDoc", this.id)
          .then((res) => {
            console.log(res);
            this.detail = res.data;
          });
    },
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      return value
    },
    changePage(e) {
      this.current = e.current - 1;
    },
    updateForm(form) {
      this.form = form;
    },
    checkboxChange(event) {
      console.log(event);
    },
    //勾选协议
    changeState() {
      this.radiovalue = !this.radiovalue;
    },
    submit() {
      if (!this.radiovalue) {
        uni.showToast({
          title: "请勾选协议",
          icon: "none",
        });
        return;
      }
      let price = this.detail.fileAmount;
      switch (this.user.vipId) {
        case "0":
          price = this.detail.price;
          break;
        case "1":
          //取两位小数
          price = (
              this.detail.fileAmount - this.detail.fileAmount * (this.detail.vipDiscount / 100)
          ).toFixed(2);
          break;
        case "2":
          price = (this.detail.fileAmount - this.detail.fileAmount * (this.detail.svipDiscount / 100)).toFixed(2);
          break;
        default:
          price = this.detail.fileAmount;
          break;
      }
      const that = this;

      this.$store
          .dispatch("CreateDocumentOrder", price)
          .then((res) => {
            console.log("生成订单成功", res);
            that.orderNumber = res.data.orderNumber;
            uni.requestPayment({
              provider: "wxpay",
              timeStamp: res.data.payParams.timeStamp,
              nonceStr: res.data.payParams.nonceStr,
              package: res.data.payParams.package,
              signType: res.data.payParams.signType,
              paySign: res.data.payParams.paySign,
              success: function (res) {
                console.log("success:" + JSON.stringify(res));
                that.otherDoc();
              },
              fail: function (err) {
                console.log("fail:" + JSON.stringify(err));
              },
            });
          });

    },
    otherDoc() {
      let intrestStandard = this.form.interest == '无利息' ? "" : this.form.interestTemp;
      let data = {};
      if (!isEmptyString(this.form.repayType)) {
        data.借款交付方式 = this.form.repayType;
      }
      if (!isEmptyString(this.form.owedTime)) {
        data.借款日期 = this.form.owedTime;
      }
      if (!isEmptyString(this.form.owedUse)) {
        data.借款用途 = this.form.owedUse;
      }
      if (!isEmptyString(this.form.owedMoney)) {
        data.借款金额 = this.form.owedMoney;
      }
      if (!isEmptyString(intrestStandard)) {
        data.利息标准 = intrestStandard;
      }
      if (!isEmptyString(this.form.plaintiffAddress)) {
        data.原告住址 = this.form.plaintiffAddress;
      }
      if (!isEmptyString(this.form.plaintiffName)) {
        data.原告姓名 = this.form.plaintiffName;
      }
      if (!isEmptyString(this.form.plaintiffSex)) {
        data.原告性别 = this.form.plaintiffSex;
      }
      if (!isEmptyString(this.form.plaintiffPhone)) {
        data.原告电话 = this.form.plaintiffPhone;
      }
      if (!isEmptyString(this.form.plaintiffID)) {
        data.原告身份证号 = this.form.plaintiffID;
      }
      if (!isEmptyString(this.form.interestAll)) {
        data.支付利息总额 = this.form.interestAll;
      }
      if (!isEmptyString(this.form.repaymentTime)) {
        data.约定还款时间 = this.form.repaymentTime;
      }
      if (!isEmptyString(this.form.defendantAddress)) {
        data.被告住址 = this.form.defendantAddress;
      }
      if (!isEmptyString(this.form.defendantName)) {
        data.被告姓名 = this.form.defendantName;
      }
      if (!isEmptyString(this.form.defendantSex)) {
        data.被告性别 = this.form.defendantSex;
      }
      if (!isEmptyString(this.form.defendantPhone)) {
        data.被告电话 = this.form.defendantPhone;
      }
      if (!isEmptyString(this.form.defendantID)) {
        data.被告身份证号 = this.form.defendantID;
      }
      if (!isEmptyString(this.form.lawsuitType)) {
        data.诉状类型 = this.form.lawsuitType;
        console.log("诉状类型", this.form.lawsuitType);
      }
      if (!isEmptyString(this.form.owedMoney)) {
        data.诉讼标的额 = this.form.owedMoney;
      }
      if (!isEmptyString(this.form.IOUs)) {
        data.借据类型 = this.form.IOUs;
      }
      //下载文件的url
      let url = "";
      let id = "";
      const that = this;
      console.log("data", data);

      this.$store.dispatch("GenerateDoc", data).then(
          (res) => {
            id = res.data;
            url = config.baseUrl + "/file/fileGenerate?id=" + id + "&bigType=" +
                that.detail.bigType + "&orderNumber=" + that.orderNumber+"&smallType="+that.detail.smallType;
            uni.downloadFile({
              url: url,//下载地址接口返回
              success: (data) => {
                if (data.statusCode === 200) {
                  //文件保存到本地
                  console.log("data.tempFilePath", data.tempFilePath);
                  console.log("data", data);
                  //将tempFilePath中改成docx
                  let tempFilePath = data.tempFilePath;
                  let index = tempFilePath.lastIndexOf(".");
                  let str = tempFilePath.substring(0, index);
                  let newTempFilePath = str + ".docx";
                  uni.saveFile({
                    tempFilePath: newTempFilePath, //临时路径
                    success: function (res) {
                      uni.showToast({
                        icon: 'none',
                        mask: true,
                        title: '文件已保存：' + res.savedFilePath, //保存路径
                        duration: 3000,
                      });
                      setTimeout(() => {
                        that.previewAll(res)
                      }, 3000)
                      //清空form表单
                      that.form = {
                        repayType: "",
                        owedTime: "",
                        owedUse: "",
                        owedMoney: "",
                        interest: "",
                        standard: "",
                        plaintiffAddress: "",
                        plaintiffName: "",
                        plaintiffSex: "",
                        plaintiffPhone: "",
                        plaintiffID: "",
                        interestAll: "",
                        repaymentTime: "",
                        defendantAddress: "",
                        defendantName: "",
                        defendantSex: "",
                        defendantPhone: "",
                        defendantID: "",
                        lawsuitType: "",
                        IOUs: "",
                      };
                    }
                  });
                }
              },
              fail: (err) => {
                console.log(err);
                uni.showToast({
                  icon: 'none',
                  mask: true,
                  title: '失败请重新下载',
                });
              }
            });

          }
      ).catch();
    },
    // 预览文件
    previewAll(res) {
      let url = res.savedFilePath;
      //将url中改成docx
      let index = url.lastIndexOf(".");
      let str = url.substring(0, index);
      let newUrl = str + ".docx";
      if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)) { //图片预览
        uni.previewImage({
          urls: [url],
          longPressActions: {
            itemList: ['发送给朋友', '保存图片', '收藏'],
            success: function (data) {
            },
            fail: function (err) {
              console.log(err.errMsg);
            }
          }
        });
      } else { //文件预览
        uni.openDocument({
          showMenu: true,
          filePath: newUrl,
          success: function (res) {
            console.log('打开文档成功');
          },
          fail: (err) => {
            uni.showToast({
              title: '打开文件失败请重试',
              icon: 'none'
            })
          }
        });
      }
    },

  },
};
</script>

<style lang="scss">
page {
  background-color: #f5f7fa;
}

.law-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .top {
    height: 8rem;
    position: relative;
    background-size: 100% 100% !important;
    display: flex;
    flex-direction: column;
    align-items: center;

    .title {
      font-size: 1.5rem;
      color: #ffffff;
      margin-top: 1rem;
    }

    .sub-title {
      font-size: 1rem;
      color: #ffffff;
      margin-top: 0.5rem;
    }
  }

  .example {
    width: 95%;
    background-color: #ffffff;
    border-radius: 10px;
    position: absolute;
    left: 2%;
    top: 6rem;
    padding: 1rem;
    padding-left: 1rem;

    .content {
      margin-bottom: 1rem;
    }

    .flex-row {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-top: 0.5rem;
      margin-bottom: 0.5rem;

      text {
        color: #999;
      }
    }

    .flex-column {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 0.5rem;
      margin-bottom: 0.5rem;
      text-align: center;

      text {
        color: #999;
      }
    }
  }

  .marginTop {
    margin-top: 0.5rem;

    .radio {
      width: 30rpx;
      height: 30rpx;
      border-radius: 50%;
      border: 1px solid #999;
    }

    .radio-checked {
      width: 30rpx;
      height: 30rpx;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #e43d33;
    }
  }

  .bottom {
    margin-top: 1rem;
  }
}
</style>
